﻿using IOP.OpenType.Tables;
using IOP.OpenType;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace IOP.Codec.OpenType
{
    /// <summary>
    /// 
    /// </summary>
    public class LocaTableLoader
    {
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="stream">字节流</param>
        /// <param name="entry">表入口</param>
        /// <param name="indexToLocFormat"></param>
        /// <param name="numGlyphs">字形数量</param>
        /// <param name="maxOffset">最大偏移</param>
        /// <returns></returns>
        public async Task<LocaTable> Load(FileStream stream, TableEntry entry, short indexToLocFormat, ushort numGlyphs, uint maxOffset)
        {
            uint offset = entry.Offset;
            stream.Seek(offset, SeekOrigin.Begin);
            var pipe = new Pipe();
            var w = WriteToPipe(stream, pipe.Writer, entry);
            var r = ReadFromPipe(pipe.Reader, entry, indexToLocFormat, numGlyphs, maxOffset);
            await Task.WhenAll(w, r);
            LocaTable table = r.Result;
            return table;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private async Task WriteToPipe(Stream stream, PipeWriter writer, TableEntry entry)
        {
            try
            {
                long already = 0;
                while (true)
                {
                    Memory<byte> memory = writer.GetMemory(2048);
                    int bytesRead = await stream.ReadAsync(memory);
                    writer.Advance(bytesRead);
                    already += bytesRead;
                    if (bytesRead == 0 || already >= entry.Length) break;
                    FlushResult result = await writer.FlushAsync();
                    if (result.IsCompleted) break;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                writer.Complete();
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private async Task<LocaTable> ReadFromPipe(PipeReader reader, TableEntry entry, short indexToLocFormat, ushort numGlyphs, uint maxOffset)
        {
            try
            {
                LocaTable table = new LocaTable();
                table.Entry = entry;
                table.Offsets = new Offset32[numGlyphs + 1];
                table.MaxOffset = maxOffset;
                long finalBytes = entry.Length;
                long byteIndex = 0;
                long consumed = 0;
                int index = 0;
                while (true)
                {
                    ReadResult result = await reader.ReadAsync();
                    ReadOnlySequence<byte> buffer = result.Buffer;
                    ReadOffset(ref buffer, ref byteIndex, ref index, table, indexToLocFormat);
                    consumed += byteIndex;
                    reader.AdvanceTo(buffer.GetPosition(byteIndex));
                    if (consumed >= finalBytes || index >= numGlyphs + 1) 
                        break;
                    byteIndex = 0;
                }
                return table;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Complete();
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void ReadOffset(ref ReadOnlySequence<byte> buffer, ref long byteIndex, ref int index, LocaTable table, short indexToLocFormat)
        {
            SequenceReader<byte> reader = new SequenceReader<byte>(buffer);
            reader.Advance(byteIndex);
            int length = table.Offsets.Length;
            if(indexToLocFormat == 0)
            {
                while(reader.Remaining >= sizeof(ushort) && index < length)
                {
                    reader.TryReadBigEndian(out short local);
                    table.Offsets[index++] = local;
                    byteIndex += sizeof(ushort);
                }
            }
            else
            {
                while(reader.Remaining >= sizeof(uint) && index < length)
                {
                    reader.TryReadBigEndian(out int local);
                    table.Offsets[index++] = local;
                    byteIndex += sizeof(uint);
                }
            }
        }
    }
}
